# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 13:44:05 2021

@author: ckpark
"""

import os
os.environ["PROJ_LIB"] = r'C:\Users\ckpark\anaconda3\Library\share'

from netCDF4 import Dataset
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import sys
import matplotlib.gridspec as gridspec
from scipy.stats import linregress
import matplotlib.colors as mc
from matplotlib.patches import Polygon
import matplotlib as m
import matplotlib
from scipy import stats
import scipy.signal
import scipy.signal as signal

def init_plotting():
    plt.rcParams['font.family'] = 'Times New Roman'
init_plotting()


calend = ['1/1/2021','6/1/2021','1/1/2022','6/1/2022','12/1/2022','12/31/2022']
xlabs = ['JAN'+'\n'+'2021','JUN'+'\n'+'2021','JAN'+'\n'+'2022','JUN'+'\n'+'2022','DEC'+'\n'+'2022']
#calend = ['4/18/1942','4/18/1943','4/6/1944','5/9/1944']
#################################################################
def moving(inte, n):
    result = np.convolve(inte, np.ones((n,))/n, mode='same')
    return result

def passfuc(nt,dat):
    fs = nt
    # First, design the Buterworth filter
    N  = 5    # Filter order

    #cut = ((fs)/float(cutoff))
    cut = 10.0
    Wn = cut / (fs/2.0) # Cutoff frequency
    B, A = signal.butter(N, Wn, btype='low',output='ba')
    # Second, apply the filter
    rdat = signal.filtfilt(B,A, dat)
    return rdat
#################################################################
######################################
read = np.loadtxt('./RESULT/EDI_47156', dtype='str')
yr = np.array(read[1:,0], dtype='int')
mo = np.array(read[1:,1], dtype='int')
dy = np.array(read[1:,2], dtype='int')
edi = np.array(read[1:,3], dtype='float')
pre = np.array(read[1:,4], dtype='float')

read = np.loadtxt('../DATA/google_KO.txt', dtype='str')
gdate_ko = np.array(read[:,0], dtype='str')
g_ko = np.array(read[:,1], dtype='float')

read = np.loadtxt('../DATA/google_GJ.txt', dtype='str')
gdate_gj = np.array(read[:,0], dtype='str')
g_gj = np.array(read[:,1], dtype='float')

read = np.loadtxt('../DATA/naver_KO.txt', dtype='str')
ndate = np.array(read[:,0], dtype='str')
n_ko = np.array(read[:,1], dtype='float')

rg_ko = []; rg_gj = []; rn_ko = []
gko = -999.0; ggj = -999.0; nko = -999.0
for t in range(len(yr)):
    for i in range(len(gdate_ko)):
        var = gdate_ko[i].split('-')
        gyr = int(var[0]); gmo = int(var[1]); gdy = int(var[2])
        
        if yr[t] == gyr and mo[t] == gmo and dy[t] == gdy:
            gko = g_ko[i]
    rg_ko.append(gko)
        
    for i in range(len(gdate_gj)):
        var = gdate_gj[i].split('-')
        gyr = int(var[0]); gmo = int(var[1]); gdy = int(var[2])
        
        if yr[t] == gyr and mo[t] == gmo and dy[t] == gdy:
            ggj = g_gj[i]
    rg_gj.append(ggj)
    
    for i in range(len(ndate)):
        var = ndate[i].split('-')
        gyr = int(var[0]); gmo = int(var[1]); gdy = int(var[2])
        
        if yr[t] == gyr and mo[t] == gmo and dy[t] == gdy:
            nko = n_ko[i]
    rn_ko.append(nko)    


dates = []
for t in range(len(yr)):
    for k in range(len(calend)):
        var = calend[k].split('/')
        year = int(var[-1]); month = int(var[0]); day = int(var[1])
        if (yr[t] == year) and (mo[t] == month) and (dy[t] == day):
            dates.append(t)        

edi = edi[dates[0]:dates[-1]+1]
pre = pre[dates[0]:dates[-1]+1]

rg_ko = rg_ko[dates[0]:dates[-1]+1]
rg_gj = rg_gj[dates[0]:dates[-1]+1]
rn_ko = rn_ko[dates[0]:dates[-1]+1]

rg_ko = np.ma.masked_values(rg_ko, -999.0)
rg_gj = np.ma.masked_values(rg_gj, -999.0)
rn_ko = np.ma.masked_values(rn_ko, -999.0)

nt = dates[-1] - dates[0] + 1

############## PDO FIG #############
fig = plt.figure(figsize=(10,10))
for xx in range(1):
    ax1 = fig.add_subplot(3,1,xx+1)

    xax = np.arange(0,nt)
    ax1.set_xlim(0,nt-1)
    ax1.set_yticks(np.arange(-10.0,10.0,1.0))
    ax1.set_ylim(-3.5,3.4)
  
    xlab = calend[:-1]
    xtick = np.array(dates[:-1]) - dates[0]

    ax1.set_xticks(xtick)
    ax1.set_xticklabels(xlabs)
    ax1.set_xlabel('Date',fontsize=26)    
    #plt.xticks(rotation=45)
    
    ax1.axhline(y=0.0, color='black', linestyle='solid')
    #ax1.axhline(y=-0.5, color='red', linestyle='dashed')

    ax1.plot(xax,edi,color='black',zorder=10,alpha=1.0)
    #ax1.plot(xax,macd_rpdo,color='blue',zorder=1,alpha=1.0)
    ax1.set_ylabel('Index',fontsize=24)
    ax1.tick_params(labelsize=23)

    #ax1.axvline(x=xtick[1], color='black', linestyle='solid')
    #ax1.axvline(x=xtick[2], color='black', linestyle='solid')
    #ax1.axvline(x=276, color='black', linestyle='solid')
    
    ######
    ax2 = ax1.twinx()
    
    ax2.set_yticks(np.arange(0,500,20))
    ax2.set_ylim(0,100)
    
    ax2.plot(xax,rg_ko,color='blue',zorder=1,alpha=0.8)
    #ax2.plot(xax,rg_gj,color='orange',zorder=1,alpha=0.8)
    ax2.plot(xax,rn_ko,color='green',zorder=1,alpha=0.8)
    ax2.set_ylabel('Search frequency',fontsize=24)
    ax2.tick_params(labelsize=25)

plt.subplots_adjust(hspace=0.0,wspace=0.2)
plt.show()
outfig = '../99.FIG/2022_EDI_time_series.png'      
fig.savefig(outfig,bbox_inches='tight') 
#############################################################33

